<template>
  <div ref="scrollContainer" class="scroll-container" @scroll="handleScroll">
    <div v-for="item in dataList" :key="item.id">{{ item.name }}</div>
    <div v-if="isLoading">加载中...</div>
    <div v-if="!hasMore">没有更多数据</div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import { debounce } from 'lodash';

const scrollContainer = ref(null);
const dataList = ref([]);
const currentPage = ref(1);
const isLoading = ref(false);
const hasMore = ref(true);

// 防抖处理滚动事件
const handleScroll = debounce(() => {
  const { scrollTop, clientHeight, scrollHeight } = scrollContainer.value;
  if (scrollTop + clientHeight >= scrollHeight - 50 && !isLoading.value) {
    loadMoreData();
  }
}, 200);

// 加载数据
const loadMoreData = async () => {
  isLoading.value = true;
  try {
    const res = await fetch(`/api/data?page=${currentPage.value}`);
    const newData = await res.json();
    if (newData.length === 0) {
      hasMore.value = false;
    } else {
      dataList.value = [...dataList.value, ...newData];
      currentPage.value++;
    }
  } catch (error) {
    console.error('加载失败:', error);
  }
  isLoading.value = false;
};

onMounted(() => {
  loadMoreData(); // 初始化加载
  scrollContainer.value?.addEventListener('scroll', handleScroll);
});

onUnmounted(() => {
  scrollContainer.value?.removeEventListener('scroll', handleScroll);
});
</script>
